package ee.kuli.hk.rent;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class ManageDevice extends Activity {

	private ImageView device_image = null;
	private Button add_device_btn = null;
	private Uri mImageUri = null;
	private Uri mImagePrev = null;
	private final int CAPTURE_IMAGE = 1;
	
	private EditText device_model, device_serial, device_value, device_desc;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.manage_device);
		
		device_model = (EditText) findViewById(R.id.device_model);
		device_serial = (EditText) findViewById(R.id.device_serial);
		device_value = (EditText) findViewById(R.id.device_value);
		device_desc = (EditText) findViewById(R.id.device_description);
		
		device_image = (ImageView) findViewById(R.id.device_image);
		device_image.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				File photo;
				try {
					// place where to store camera taken picture
					photo = createTemporaryFile("picture", ".jpg");
					photo.delete();
				} catch (Exception e) {
					Log.v("hk-rent", "Can't create file to take picture!");
					Toast.makeText(getApplicationContext(),
							"Please check SD card! Image shot is impossible!",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (mImageUri != null) {
					mImagePrev = mImageUri;
				}
				mImageUri = Uri.fromFile(photo);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);

				startActivityForResult(intent, CAPTURE_IMAGE);
			}
		});

		add_device_btn = (Button) findViewById(R.id.add_device_btn);
		add_device_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Create a new HttpClient and Post Header
				HttpParams params = new BasicHttpParams();
				HttpProtocolParams.setContentCharset(params, "UTF-8");
				HttpProtocolParams.setHttpElementCharset(params, "UTF-8");
				
				HttpClient httpclient = new DefaultHttpClient(params);
				HttpPost httppost = null;
				try {
					httppost = new HttpPost(new URI(
							"http://192.168.0.12/rent/service.php"));
				} catch (URISyntaxException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				try {

					MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

					if (mImageUri != null) {
						getContentResolver().notifyChange(mImageUri, null);
						ContentResolver cr = getContentResolver();
						Bitmap bitmap;
						byte[] byteArray = null;
						try {
							bitmap = resize(1280, android.provider.MediaStore.Images.Media.getBitmap(cr, mImageUri));
							byteArray = compressToBytes(bitmap);
						} catch (Exception e) {

						}
						if (byteArray != null) {
							InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(byteArray), "device_image");

							reqEntity.addPart("device_image_uploaded", isb);
						}
					}		

					reqEntity.addPart("device_model", new StringBody(device_model.getText().toString(), Charset.forName("UTF-8")));
					reqEntity.addPart("device_serial", new StringBody(device_serial.getText().toString(), Charset.forName("UTF-8")));
					reqEntity.addPart("device_value", new StringBody(device_value.getText().toString(), Charset.forName("UTF-8")));
					reqEntity.addPart("device_description", new StringBody(device_desc.getText().toString(), Charset.forName("UTF-8")));
					reqEntity.addPart("service_action", new StringBody("1", Charset.forName("UTF-8"))); //Add device ACTION == 1
					httppost.setEntity(reqEntity);

					// Execute HTTP Post Request
					BasicResponseHandler handler = new BasicResponseHandler();
					String response = httpclient.execute(httppost, handler);

					Log.i("hk-rent", response);

				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CAPTURE_IMAGE) {
			if (resultCode == Activity.RESULT_OK) {
				grabImage(device_image);
			} else {
				if (mImagePrev != null) {
					mImageUri = mImagePrev;
				}
				Toast.makeText(this, "Picture was not saved",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	private File createTemporaryFile(String part, String ext) throws Exception {
		File tempDir = Environment.getExternalStorageDirectory();
		tempDir = new File(tempDir.getAbsolutePath() + "/.hk_rent/");
		if (!tempDir.exists()) {
			tempDir.mkdir();
		}
		return File.createTempFile(part, ext, tempDir);
	}

	public void grabImage(ImageView imageView) {
		getContentResolver().notifyChange(mImageUri, null);
		ContentResolver cr = getContentResolver();
		Bitmap bitmap;
		try {
			bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr,
					mImageUri);

			imageView.setImageBitmap(resize(1280, bitmap));
		} catch (Exception e) {
			Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
			Log.d("hk-rent", "Failed to load", e);
		}
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		String imageUri = savedInstanceState.getString("mImage");
		if (imageUri != null) {
			mImageUri = Uri.parse(imageUri);
			grabImage(device_image);
		}
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		if (mImageUri != null) {
			outState.putString("mImage", mImageUri.toString());
		}
		super.onSaveInstanceState(outState);
	}
	
	public static Bitmap resize(int newHeight, Bitmap bitmapOrig) {    
	    float ratio = (float) bitmapOrig.getWidth() / (float) bitmapOrig.getHeight(); //Have to cast to float, otherwise not working
	    float scaleWidth = newHeight * ratio;
	    float scaleHeight = newHeight;
	    Bitmap bm = Bitmap.createScaledBitmap(bitmapOrig, (int) scaleWidth, (int) scaleHeight, true);
	    return bm;
	}
	
	private byte[] compressToBytes(Bitmap bm) {
	    ByteArrayOutputStream stream = new ByteArrayOutputStream();
	    bm.compress(Bitmap.CompressFormat.JPEG, 80, stream);
	    byte[] bmBytes = stream.toByteArray();
	    return bmBytes;
	}

}
